package com.futurescale.sa.model.vo
{
	import com.futurescale.sa.model.enum.StoryTypeEnum;

	public class SeasonVO extends ValueObject
	{
		/**
		 * The XML element name.
		 */
		public static const ELEMENT:String = "Season";
		
		/**
		 * Construct a SeasonVO. 
		 */
		public function SeasonVO( xml:XML=null )
		{
			super( ELEMENT, xml );
		}
		
		/**
		 * The Series stub
		 */ 
		public function get series():SeriesVO
		{
			return ( x.Series[0] )?new SeriesVO( x.Series[0] ):null;
		}
		public function set series( s:SeriesVO ):void
		{
			x.Series = s.xml;
		}

		/**
		 * Story type to be used for each new Story.
		 * StoryTypeEnum.SIMPLE  = Scenes only (the default if using seasons)
		 * StoryTypeEnum.NORMAL  = Chapters, and Scenes (the default if not using seasons)
		 * StoryTypeEnum.COMPLEX = Parts, Chapters, and Scenes 
		 */ 
		public function get storyType():StoryTypeEnum
		{
			var defaultType:StoryTypeEnum = StoryTypeEnum.SIMPLE;
			return ( x.@storyType!=undefined ) ? StoryTypeEnum.list[ Number( x.@storyType ) ] : defaultType; 
		}
		public function set storyType( t:StoryTypeEnum ):void
		{
			x.@storyType = t.ordinal;
		}
		
		/**
		 * Get a new Story for the Season.
		 */
		public function getNewStory( ):StoryVO
		{
			var story:StoryVO = new StoryVO();
			story.type 		  = storyType;
			addStory( story );
			return story;
		}
		
		/**
		 * Add a Story to the Season, renumbering the existing
		 * stories if the added story already has an ordinal less
		 * than the next story ordinal.
		 * 
		 * Sets Series, Cast, and Milieu stubs on Story
		 */
		public function addStory( story:StoryVO ):void
		{
			story.series    = new SeriesVO( this.getStub() );
			story.cast      = series.cast;
			story.milieu    = series.milieu;
			
			if ( story.ordinal > 0 && story.ordinal < nextStoryOrdinal ) {
				var stories:Vector.<StoryVO> = this.stories;
				for each (var svo:StoryVO in stories ){
					if (svo.ordinal >= story.ordinal) svo.ordinal = svo.ordinal+1;
				}
			} else {
				story.ordinal = nextStoryOrdinal;
			}
			xml.appendChild( story.xml );
		}
		/** 
		 * An ordinal-sorted Vector of this Season's 
		 * Episodes.
		 */
		public function get stories():Vector.<StoryVO>
		{
			var v:Vector.<StoryVO> = new Vector.<StoryVO>();
			var xl:XMLList = xml.child(StoryVO.ELEMENT);
			for each ( var ex:XML in xl ) {
				var episode:StoryVO = new StoryVO(ex);
				v.push(episode);
			}
			v.sort(ValueObject.ordinalSort);
			return v;
		}
		public function set stories( v:Vector.<StoryVO> ):void
		{} // readonly but bindable
		
		
		/**
		 * Get the next Story ordinal for this Season.
		 */
		private function get nextStoryOrdinal():Number
		{
			return getNextOrdinal( xml..Story );
		}
	}
}